package com.muyan.sys.webscoket.service;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson2.JSON;
import com.muyan.sys.common.core.redis.RedisCache;
import com.muyan.sys.common.utils.DateUtils;
import com.muyan.sys.webscoket.constant.ChatCacheConstants;
import com.muyan.sys.webscoket.entity.ChatGroup;
import com.muyan.sys.webscoket.protocol.MessageProto;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.temporal.ChronoUnit;
import java.util.Date;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class ChatGroupService {


    @Autowired
    private RedisCache redisCache;




    @Autowired
    private RabbitTemplate rabbitTemplate;



    /**
     * 创建群组
     */
    public ChatGroup createGroup(String groupName, String creatorId, String description, Date endtime) {
        ChatGroup group = new ChatGroup();
        group.setGroupId(UUID.randomUUID().toString());
        group.setGroupName(groupName);
        group.setCreatorId(creatorId);
        group.setDescription(description);
        group.setMaxMembers(200);

        // 将群组信息存储到Redis Hash结构中
        String groupInfoKey = ChatCacheConstants.GROUP_INFO_KEY + group.getGroupId();
        redisCache.setCacheMapValue(groupInfoKey, "name", groupName);
        redisCache.setCacheMapValue(groupInfoKey, "creator", creatorId);
        redisCache.setCacheMapValue(groupInfoKey, "description", description);
        redisCache.setCacheMapValue(groupInfoKey, "maxMembers", "200");
        redisCache.setCacheMapValue(groupInfoKey, "createTime", String.valueOf(System.currentTimeMillis()));
        redisCache.setCacheMapValue(groupInfoKey, "expireTime", DateUtils.addDays(endtime,1));

        // 将创建者添加为群成员和管理员
        addGroupMember(group.getGroupId(), creatorId);
        redisCache.setCacheSetAdd(ChatCacheConstants.GROUP_ADMIN_KEY + group.getGroupId(), creatorId);
        //群组过期时间为 活动过后一天
        redisCache.expire(groupInfoKey, calculateHoursDifference(DateUtils.addDays(endtime,1)), TimeUnit.HOURS); // 设置30天过期时间


        MessageProto message=new MessageProto();
        message.setGroupId(group.getGroupId());
        message.setToUserId(creatorId);
        message.setFromNickname(groupName);


        // 用户在其他服务器，通过RabbitMQ发送消息
        rabbitTemplate.convertAndSend(
                ChatCacheConstants.MQ_GROUP_WS_EXCHANGE,
                JSON.toJSONString(group)
        );

        return group;
    }

    public static long calculateHoursDifference(Date givenDate) {
        Instant instant = givenDate.toInstant();
        LocalDateTime givenTime = instant.atZone(ZoneId.systemDefault()).toLocalDateTime();
        LocalDateTime currentTime = LocalDateTime.now();
        return ChronoUnit.HOURS.between(currentTime, givenTime);
    }

    /**
     * 添加群成员
     */
    public void addGroupMember(String groupId, String userId) {
        // 检查群组是否存在
        if (!isGroupExists(groupId)) {
            throw new RuntimeException("群组不存在");
        }

        // 检查群组人数是否已满
        Long memberCount = redisCache.getCacheSetSize(ChatCacheConstants.GROUP_MEMBERS_KEY + groupId);
        String maxMembersStr = redisCache.getCacheMapValue(ChatCacheConstants.GROUP_INFO_KEY + groupId, "maxMembers");
        int maxMembers = Integer.parseInt(maxMembersStr != null ? maxMembersStr : "200");

        if (memberCount != null && memberCount >= maxMembers) {
            throw new RuntimeException("群组已满");
        }

        // 添加成员到Redis Set

        redisCache.setCacheSetAdd(ChatCacheConstants.GROUP_MEMBERS_KEY + groupId, userId);

        // 更新加入时间
        redisCache.setCacheMapValue(
                ChatCacheConstants.GROUP_INFO_KEY + groupId + ":members",
                userId,
                String.valueOf(System.currentTimeMillis())
        );
    }

    /**
     * 移除群成员
     */
    public void removeGroupMember(String groupId, String userId) {
        // 检查是否是群主
        String creator = redisCache.getCacheMapValue(ChatCacheConstants.GROUP_INFO_KEY + groupId, "creator");
        if (creator != null && creator.equals(userId)) {
            throw new RuntimeException("群主不能退出群组");
        }
        redisCache.deletCacheSet(ChatCacheConstants.GROUP_MEMBERS_KEY + groupId, userId);

        // 从Redis Set中移除成员
        redisCache.deletCacheSet(ChatCacheConstants.GROUP_MEMBERS_KEY + groupId, userId);
        // 如果是管理员，也要移除管理员身份
        redisCache.deletCacheSet(ChatCacheConstants.GROUP_ADMIN_KEY + groupId, userId);
        // 移除成员信息

        redisCache.deleteCacheMapValue(ChatCacheConstants.GROUP_INFO_KEY + groupId + ":members", userId);
    }

    /**
     * 获取群成员列表
     */
    public Set<String> getGroupMembers(String groupId) {
        // 从Redis Set中获取所有成员
        return redisCache.getCacheSet(ChatCacheConstants.GROUP_MEMBERS_KEY + groupId);
    }

    /*   *//**
     * 获取群成员详细信息
     *//*
    public List<GroupMemberInfo> getGroupMemberDetails(String groupId) {
        Set<String> memberIds = getGroupMembers(groupId);
        if (memberIds == null || memberIds.isEmpty()) {
            return Collections.emptyList();
        }

        List<GroupMemberInfo> memberInfos = new ArrayList<>();
        String creator = (String) redisTemplate.opsForHash().get(GROUP_INFO_KEY + groupId, "creator");
        Set<String> admins = redisTemplate.opsForSet().members(GROUP_ADMIN_KEY + groupId);

        for (String memberId : memberIds) {
            GroupMemberInfo memberInfo = new GroupMemberInfo();
            memberInfo.setUserId(memberId);

            // 设置角色
            if (memberId.equals(creator)) {
                memberInfo.setRole("CREATOR");
            } else if (admins != null && admins.contains(memberId)) {
                memberInfo.setRole("ADMIN");
            } else {
                memberInfo.setRole("MEMBER");
            }

            // 获取加入时间
            String joinTime = (String) redisTemplate.opsForHash().get(
                    GROUP_INFO_KEY + groupId + ":members",
                    memberId
            );
            memberInfo.setJoinTime(joinTime != null ? Long.parseLong(joinTime) : 0);

            memberInfos.add(memberInfo);
        }

        return memberInfos;
    }*/

    /**
     * 检查用户是否是群成员
     */
    public boolean isGroupMember(String groupId, String userId) {
        return Boolean.TRUE.equals(redisCache.isSetMember(ChatCacheConstants.GROUP_MEMBERS_KEY + groupId, userId));
    }

    /**
     * 检查群组是否存在
     */
    private boolean isGroupExists(String groupId) {
        return Boolean.TRUE.equals(redisCache.hasKey(ChatCacheConstants.GROUP_INFO_KEY + groupId));
    }

    /**
     * 解散群组
     */
    public void dissolveGroup(String groupId) {
        // 检查操作者是否是群主
        String creator = redisCache.getCacheMapValue(ChatCacheConstants.GROUP_INFO_KEY + groupId, "creator");

        if (creator == null) {
            throw new RuntimeException("群组不存在");
        }

        // 删除所有相关的Redis键
        redisCache.deleteObject(ChatCacheConstants.GROUP_MEMBERS_KEY + groupId);
        redisCache.deleteObject(ChatCacheConstants.GROUP_MEMBERS_KEY + groupId);
        redisCache.deleteObject(ChatCacheConstants.GROUP_ADMIN_KEY + groupId);
        redisCache.deleteObject(ChatCacheConstants.GROUP_INFO_KEY + groupId);
        redisCache.deleteObject(ChatCacheConstants.GROUP_INFO_KEY + groupId + ":members");
    }

}